<?php

namespace app\api\controller\dynamic;

use app\api\controller\Common;
use app\api\model\DymanicUserlover;
use app\api\model\DymanicUserthumbsup;
use think\Db;
use think\Validate;

class Mix extends Common {
    /**
     * @var array
     */
    protected $rule = [
        'title'       => 'require|length:2,20',
        'description' => 'length:5,200',
        'cover'       => 'require|length:2,255',
        'id'          => 'gt:0',
    ];
    /**
     * @var array
     */
    protected $msg = [
        'title.require'      => '请输入合集标题',
        'title.length'       => '合集标题字数要求2-20字',
        'description.length' => '合集简介字数要求5-200字',
        'cover.require'      => '请上传合集封面',
        'cover.length'       => '合集封面异常',
        'id.gt'              => '参数异常',
    ];
    /**
     * @return mixed
     */
    public function create() {
        $post = input('post.');
        $data = [
            'title'       => $post['title'] ?? '',
            'description' => $post['description'] ?? '',
            'cover'       => $post['cover'] ?? '',
            'state'       => 1,
            'user_id'     => $this->member['id'],
            'create_time' => time(),
        ];
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        }

        $hasTitle = Db::name('dymanic_collection')->where(['user_id' => $this->member['id'], 'title' => $data['title']])->find();
        if ($hasTitle) {
            return $this->miss('合集名称已经存在');
        }
        $count        = Db::name('dymanic_collection')->where(['user_id' => $this->member['id']])->count();
        $data['sort'] = $count + 1;

        if ($post['dy_ids']) {
            $result = $this->termSortValid(['id' => 0], $post['dy_ids']);
            if ($result) {
                return $this->miss($result);
            }
        }

        $check_dymanic_mix = Db::name('config_system')->where(['title' => 'check_dymanic_mix'])->value('content');
        if ($check_dymanic_mix) {
            $data['state'] = 0;
        }

        $res = Db::name('dymanic_collection')->insertGetId($data);
        if (!$res) {
            return $this->miss('创建失败');
        }
        $info['id'] = $res;
        if ($post['dy_ids']) {
            $result = $this->termSort($info, $post['dy_ids']);
            if ($result) {
                return $this->miss($result);
            }
        }
        return $this->pass('创建成功' . ($check_dymanic_mix ? ',等待审核' : ''));
    }

    public function list() {
        $to      = input('to');
        $user_id = $to ? $to : $this->member['id'];
        $where   = ['user_id' => $user_id];
        if ($to && $to != $this->member['id']) {
            $where['count'] = ['>', 0];
        }
        $data = Db::name('dymanic_collection')
            ->where($where)
            ->field('id,title,description,cover,count,lover,visit,create_time')
            ->order('sort desc')
            ->select();

        foreach ($data as &$value) {
            // $value['cover']       = _ossUrl() . $value['cover'];
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $mix_ids
     * @return mixed
     */
    public function sort($mix_ids = '') {
        $all = Db::name('dymanic_collection')->where(['user_id' => $this->member['id']])->column('id,sort');
        $ids = explode(',', $mix_ids);

        if (sizeof(array_diff($ids, array_keys($all))) || sizeof(array_diff(array_keys($all), $ids))) {
            return $this->miss('数据异常');
        }

        $data   = [];
        $length = sizeof($ids);
        foreach ($ids as $key => $value) {
            $state = Db::name('dymanic_collection')->where(['id' => $ids[$key]])->update(['sort' => $length - $key]);
            if ($state) {
                $res = true;
            }

        }
        return $this->pass('success');
    }

    /**
     * @param $id
     * @return mixed
     */
    public function info($id = '') {
        $data = Db::name('dymanic_collection')->field('sort,update_time', 'filter')->find($id);
        if (!$data) {
            return $this->miss('合集不存在');
        }
        if ($data['user_id'] != $this->member['id']) {
            if ($data['state'] != 1 || !$data['count']) {
                return $this->miss('合集不存在');
            }
        }
        $dy_ids = Db::name('dymanic_collection_term')->where(['collection_id' => $id])->column('dy_id');
        if (sizeof($dy_ids)) {
            $visit      = Db::name('dymanic')->where(['dy_id' => ['in', $dy_ids]])->sum('visit');
            Db::name('dymanic_collection')->where(['id' => $id])->update(['visit' => $visit]);
            $data['visit'] = $visit;
        }

        $lover            = Db::name('dymanic_collection_lover')->where(['user_id' => $this->member['id'], 'collection_id' => $id])->find();
        $data['is_lover'] = $lover ? true : false;

        $data['list']        = $this->term($id, 1, false);
        $data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);
        return $this->pass($data);
    }

    /**
     * @param $id
     * @param $page
     * @param $returnJson
     * @return mixed
     */
    public function term($id = '', $page = 1, $returnJson = true) {
        $mix        = Db::name('dymanic_collection')->field('sort,update_time', 'filter')->find($id);
        $pagesize   = 20;
        $returnData = [];
        if ($page == -1) {
            $data = Db::name('dymanic_collection_term')
                ->alias('t')
                ->join('dymanic d', 't.dy_id=d.dy_id')
                ->where(['t.collection_id' => $id])
                ->order('t.sort desc')
                ->field('d.*')
                ->select();
        } else {
            $data = Db::name('dymanic_collection_term')
                ->alias('t')
                ->join('dymanic d', 't.dy_id=d.dy_id')
                ->where(['t.collection_id' => $id])
                ->order('t.sort desc')
                ->field('d.*')
                ->page($page)
                ->limit($pagesize)
                ->select();
        }
        $user = Db::name('user')->field('id, head_100 avatar, nvshen, kejian, name, age, sex,
            is_identity_authentication, attestation, constellation, noble_grade, noble_time, xuni_discount, hide_distance,
            register_datetime, realname_auth, longitude, latitude, real_avatar, auth_tag')->find($mix['user_id']);

        if (sizeof($data)) {
            $loves      = DymanicUserlover::where(['userid' => $this->member['id']])->column('dy_id');
            $thumbsups  = DymanicUserthumbsup::where(['userid' => $this->member['id']])->column('dy_id');
            $attentions = Db::name('attention')->where(['user_id' => $this->member['id']])->column('to_user');

            foreach ($data as $key => $item) {
                $item             = array_merge($item, $user);
                $data[$key]['id'] = $item['id'];

                $data[$key]['name']   = $item['name'] ?? '';
                $data[$key]['avatar'] = isset($item['avatar']) && $item['avatar'] ? changeUrl($item['avatar']) : '';
                try {
                    $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
                    $data[$key]['is_new'] = $item['register_datetime'] && (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;
                } catch (\Exception $e) {
                    $data[$key]['is_new'] = 0;
                    $data[$key]['is_vip'] = 0;
                }
                $data[$key]['auth_tag']     = $item['auth_tag'];
                $data[$key]['is_attention'] = in_array($item['userid'], $attentions) ? 1 : 0;
                $data[$key]['isthumbsup']   = in_array($item['dy_id'], $thumbsups) ? 1 : 0;
                $data[$key]['islover']      = in_array($item['dy_id'], $loves) ? 1 : 0;
                $data[$key]['real_avatar']  = $item['real_avatar'] ?? '';

                $masterimg = explode(",", $item['masterimg']);
                $masterimg = array_unique(array_filter($masterimg));
                foreach ($masterimg as $m => $n) {
                    $masterimg[$m] = changeUrl($n);
                }
                $data[$key]['masterimg'] = $masterimg;

                $sumbImage = explode(",", $item['sumbImage']);
                $sumbImage = array_unique(array_filter($sumbImage));
                foreach ($sumbImage as $m => $n) {
                    $sumbImage[$m] = changeUrl($n);
                }
                $data[$key]['sumbImage'] = $sumbImage;

                switch ((int) $item['source_type']) {
                case 1:
                    $data[$key]['source_info'] = action('api/flag/flagsInfo', ['flags_id' => $item['source_id'], 'returnJson' => false]);
                    break;
                case 3:
                    $data[$key]['source_info'] = Db::name('user_service')->where(['id' => $item['source_id']])->field('title,price,image,method')->find();
                    break;
                case 4:
                    $source_info = Db::name('activity_offline')->where(['id' => $item['source_id']])->field('address_name,sex,pay,price,content,images')->find();
                    if ($source_info && $source_info['images']) {
                        $source_info['images'] = explode(',', $source_info['images']);
                    }
                    $data[$key]['source_info'] = $source_info;
                    break;
                }

                $data[$key]['thumbsup'] += $item['xuni_thumbsup'];
                unset($data[$key]['xuni_thumbsup']);

                if ($data[$key]['topic']) {
                    $topic               = explode('#', $data[$key]['topic']);
                    $data[$key]['topic'] = [];
                    foreach ($topic as &$v) {
                        if ($v) {
                            $data[$key]['topic'][] = $v;
                        }

                    }
                } else {
                    $data[$key]['topic'] = [];
                }

                if ($data[$key]['topic_experience']) {
                    $topic_experience               = array_filter(explode('&', $data[$key]['topic_experience']));
                    $data[$key]['topic_experience'] = [];
                    foreach ($topic_experience as &$v) {
                        $data[$key]['topic_experience'][] = $v;
                    }
                } else {
                    $data[$key]['topic_experience'] = [];
                }

                $data[$key]['price'] *= getenv('APP_RATE');
                if ($data[$key]['class'] == 2 && $data[$key]['userid'] != $this->member['id']) {
                    $data[$key]['paystate'] = Db::name('order_of_subscribe')->where(['user_id' => $this->member['id'], 'dy_id' => $data[$key]['dy_id']])->count();
                } else {
                    $data[$key]['paystate'] = 1;
                }

                $returnData[] = $data[$key];
            }
        }

        if ($returnJson) {
            return $this->pass($returnData);
        }
        return $returnData;
    }

    /**
     * @return mixed
     */
    public function update() {
        $post = input('post.');
        $data = [
            'title'       => $post['title'] ?? '',
            'description' => $post['description'] ?? '',
            'cover'       => $post['cover'] ?? '',
            'update_time' => time(),
            'id'          => intval($post['id']),
        ];
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        }
        $info = Db::name('dymanic_collection')->where(['id' => $post['id'], 'user_id' => $this->member['id']])->find();
        if (!$info) {
            return $this->miss('合集不存在');
        }

        $hasMix = Db::name('dymanic_collection')->where(['user_id' => $this->member['id'], 'title' => $data['title']])->find();
        if ($hasMix && $hasMix['id'] != $post['id']) {
            return $this->miss('合集名称已经存在');
        }

        if ($post['dy_ids']) {
            $result = $this->termSortValid($info, $post['dy_ids']);
            if ($result) {
                return $this->miss($result);
            }
        }

        $data['state'] = $info['state'];
        $check_dymanic_mix = Db::name('config_system')->where(['title' => 'check_dymanic_mix'])->value('content');
        if ($check_dymanic_mix&&($info['title'] != $data['title'] || $info['description'] != $data['description'] || $info['cover'] != $data['cover'])) {
            $data['state'] = 0;
        }

        $res = Db::name('dymanic_collection')->where(['id' => $post['id']])->update($data);
        if (!$res) {
            return $this->miss('修改失败');
        }
        if ($post['dy_ids']) {
            $result = $this->termSort($info, $post['dy_ids']);
            if ($result) {
                return $this->miss($result);
            }

        }
        return $this->pass('修改成功'.($data['state']==0?',等待审核':''));
    }

    /**
     * @param $mix_info
     * @param $dy_ids
     */
    private function termSortValid($mix_info, $dy_ids) {
        $dy_ids = array_unique(array_filter(explode(',', $dy_ids)));

        $dys = Db::name('dymanic')->where(['dy_id' => ['in', $dy_ids], 'userid' => $this->member['id'], 'shenhe' => 1])->column('dy_id');
        if (sizeof($dys) != sizeof($dy_ids)) {
            return '数据异常请重试';
        }

        $mixids = Db::name('dymanic_collection_term')->where(['dy_id' => ['in', $dy_ids]])->column('collection_id');
        if (sizeof($mixids)) {
            foreach ($mixids as $key => $value) {
                if ($value != $mix_info['id']) {
                    return '部分作品已加入其它合集';
                }

            }
        }
    }

    /**
     * @param $mix_info
     * @param $dy_ids
     */
    private function termSort($mix_info, $dy_ids) {
        $dy_ids   = array_unique(array_filter(explode(',', $dy_ids)));
        $length   = sizeof($dy_ids);
        $mixdyids = Db::name('dymanic_collection_term')->where(['collection_id' => $mix_info['id']])->column('dy_id');
        $inserts  = [];
        foreach ($dy_ids as $key => $value) {
            if (in_array($value, $mixdyids)) {
                Db::name('dymanic_collection_term')->where(['collection_id' => $mix_info['id'], 'dy_id' => $value])->update(['sort' => $length - $key]);
            } else {
                $inserts[] = ['collection_id' => $mix_info['id'], 'dy_id' => $value, 'sort' => $length - $key];
            }
        }
        Db::name('dymanic_collection_term')->insertAll($inserts);
        $visit = Db::name('dymanic')->where(['dy_id'=>['in',$dy_ids]])->sum('visit');
        Db::name('dymanic_collection')->where(['id' => $mix_info['id']])->update(['count' => $length, 'visit'=>$visit]);
    }

    /**
     * @param $keyword
     * @param $must
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function dylist($keyword = '', $must = 0, $page = 1, $pagesize = 20) {
        $where = ['userid' => $this->member['id']];
        if ($keyword) {
            $where['title|content'] = ['like', '%' . $keyword . '%'];
        }
        $my_dyids  = Db::name('dymanic')->where(['userid' => $this->member['id']])->column('dy_id');
        $mix_dyids = Db::name('dymanic_collection_term')->where(['dy_id' => ['in', $my_dyids]])->column('dy_id');
        if ($must) {
            $where['shenhe']  = 1;
            $where['private'] = 0;
            $notin_mix_dyids  = array_diff($my_dyids, $mix_dyids);
            $where['dy_id']   = ['in', $notin_mix_dyids];
        }
        $data = Db::name('dymanic')
            ->where($where)
            ->field('dy_id,type,content,title,sumbImage,masterimg,video,cover,shenhe,datetime,lover,thumbsup,xuni_thumbsup,visit,comments,private')
            ->page($page)
            ->limit($pagesize)
            ->order('dy_id desc')
            ->select();

        foreach ($data as &$value) {
            $masterimg = explode(",", $value['masterimg']);
            $masterimg = array_unique(array_filter($masterimg));
            foreach ($masterimg as $m => $n) {
                $masterimg[$m] = changeUrl($n);
            }
            $value['masterimg'] = $masterimg;

            $sumbImage = explode(",", $value['sumbImage']);
            $sumbImage = array_unique(array_filter($sumbImage));
            foreach ($sumbImage as $m => $n) {
                $sumbImage[$m] = changeUrl($n);
            }
            $value['sumbImage'] = $sumbImage;

            $value['can_mix_into'] = 1;
            if ($value['shenhe'] != 1) {
                $value['can_mix_into']        = 0;
                $value['can_mix_into_reason'] = '作品审核中';
            }
            if ($value['private'] == 1) {
                $value['can_mix_into']        = 0;
                $value['can_mix_into_reason'] = '私密作品';
            }
            if (in_array($value['dy_id'], $mix_dyids)) {
                $value['can_mix_into']        = 0;
                $value['can_mix_into_reason'] = '已加入其它合集';
            }
        }

        return $this->pass($data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function delete($id = '') {
        $mix = Db::name('dymanic_collection')->where(['id' => $id, 'user_id' => $this->member['id']])->find();
        if (!$mix) {
            return $this->miss('合集不存在');
        }

        if ($mix['count']) {
            Db::name('dymanic_collection_term')->where(['collection_id' => $id])->delete();
        }
        $res = Db::name('dymanic_collection')->delete($id);
        if ($res) {
            return $this->pass('删除成功');
        }

        return $this->miss('删除失败');
    }

    /**
     * @param $type
     * @param $collection_id
     * @return mixed
     */
    public function lover($type = 1, $id) {
        $user_id = $this->member['id'];
        $mix     = Db::name('dymanic_collection')->find($id);
        if (!$mix) {
            return $this->miss('收藏失败');
        }

        switch ($type) {
        case 1:
            $has = Db::name('dymanic_collection_lover')->where(['user_id' => $user_id, 'collection_id' => $id])->count();
            if ($has) {
                return $this->pass('已收藏');
            }
            $res = Db::name('dymanic_collection_lover')->insert(['user_id' => $user_id, 'collection_id' => $id, 'time' => time()]);
            if ($res) {
                Db::name('dymanic_collection')->where(['id' => $id])->setInc('lover');

                return $this->pass('收藏成功');
            }
            return $this->miss('收藏失败');
            break;
        case 2:
            $res = Db::name('dymanic_collection_lover')->where(['user_id' => $user_id, 'collection_id' => $id])->delete();
            if ($res) {
                Db::name('dymanic_collection')->where(['id' => $id])->setDec('lover');

                return $this->pass('取消收藏成功');
            }
            return $this->miss('取消收藏失败');
        default:
            return $this->miss('操作错误');
            break;
        }
    }

    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function loved($page = 1, $pagesize = 20) {
        $data = Db::name('dymanic_collection_lover')
            ->alias('l')
            ->join('dymanic_collection m', 'm.id=l.collection_id')
            ->where(['m.state' => 1, 'm.count' => ['>', 0], 'l.user_id'=>$this->member['id']])
            ->field('m.id,m.title,m.description,m.cover,m.count,m.lover,m.visit,m.create_time')
            ->order('l.id desc')
            ->select();

        foreach ($data as &$value) {
            // $value['cover']       = _ossUrl() . $value['cover'];
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
        }
        return $this->pass($data);
    }
}